<template>
  <header
    @mouseover="projectNameEditIsShow(true)"
    @mouseout="projectNameEditIsShow(false)"
  >
    <div
      v-if="$route.name !== '图构建' && !$route.name.includes('模型训练')"
      class="header-style"
    >
      <div
        v-if="isShowBackHome"
        class="btn btn-back icon-text icon-only"
        style="padding-right: 0;"
        @click="onHistoryBack"
      >
        <div class="back-area">
          <a-icon-font class="back-icon" type="iconicon-beifen-right" />
          返回
        </div>
      </div>
      <a-tooltip
        v-if="visualizationMode === 'edit' && !nodeEditPanelIsFullScreen"
        placement="top"
      >
        <template slot="title">
          <span>{{
            collapsed ? '点击展开侧边栏菜单' : '点击收起侧边栏菜单'
          }}</span>
        </template>
        <a-button
          type="primary"
          class="collapsed-button"
          style="font-size: 18px; margin-left: 10px;"
          @click="toggleCollapsed"
        >
          <a-icon-font
            :type="!collapsed ? 'iconcebianshouqi1' : 'iconcebianzhankai'"
          />
        </a-button>
      </a-tooltip>
      <span v-if="visualizationMode === 'edit'" class="spliter">|</span>
      <a-tooltip
        v-if="
          visualizationMode === 'edit' &&
          $route.name === '数据视图' &&
          !nodeEditPanelIsFullScreen
        "
        placement="top"
      >
        <template slot="title">
          <span>{{
            isPanelCollapsed
              ? '点击收起数据源|算子面板'
              : '点击展开数据源|算子面板'
          }}</span>
        </template>
        <a-button
          type="primary"
          class="collapsed-button"
          @click="toggleSidePanelCollapsed"
        >
          <a-icon-font
            :type="
              isPanelCollapsed
                ? 'iconsuanzidaohangshouqi'
                : 'iconsuanzidaohangzhankai'
            "
          />
        </a-button>
      </a-tooltip>
      <a-tooltip
        v-else-if="visualizationMode === 'edit' && $route.name === '系统构建'"
        placement="top"
      >
        <template slot="title">
          <span>{{
            isPanelCollapsedVisualization
              ? '点击展开组件面板'
              : '点击收起组件面板'
          }}</span>
        </template>
        <a-button
          type="primary"
          class="collapsed-button"
          @click="toggleSidePanelCollapsedVisualization"
        >
          <a-icon-font
            :type="
              isPanelCollapsedVisualization
                ? 'iconsuanzidaohangshouqi'
                : 'iconsuanzidaohangzhankai'
            "
          />
        </a-button>
      </a-tooltip>
      <div
        v-if="visualizationMode === 'preview'"
        class="btn btn-back icon-text icon-only"
        @click="onBackToEdit"
      >
        <a-icon-font class="back-icon" type="iconicon-beifen-right" />
        返回编辑
      </div>
    </div>

    <div class="project-name">
      <a-popover
        trigger="hover"
        overlay-class-name="project-name-tooltipbox"
        :overlay-style="{
          width: 'auto',
          'max-width': '400px',
          'min-width': '20px',
        }"
      >
        <template slot="content">
          <span class="project-name-tooltip"
            >{{ project && project.name }}{{ graphBuildTaskName }}</span
          >
        </template>
        <span
          v-show="visualizationMode !== 'edit' || !projectNameEdit"
          :style="{
            height:
              visualizationMode !== 'edit' || !projectNameEdit ? '32px' : '0px',
          }"
          @click="changeProjectNameEditMode(visualizationMode)"
        >
          {{ project && project.name }}{{ graphBuildTaskName }}
        </span>
      </a-popover>

      <a-input
        v-show="visualizationMode === 'edit' && projectNameEdit"
        id="inputProjectName"
        :value="project && project.name"
        :max-length="50"
        class="input-project-name"
        autocomplete="off"
        auto-focus
        @keyup.enter="onUpdateProjectName"
        @blur="onUpdateProjectName"
      />
      <a-tooltip>
        <template slot="title">
          <span>点击修改</span>
        </template>
        <a-icon-font
          :style="{
            visibility:
              visualizationMode === 'edit' &&
              projectNameEditShow &&
              !projectNameEdit
                ? 'visible'
                : 'hidden',
          }"
          class="project-name-icon"
          type="iconbianjizhi-copy"
          @click="changeProjectNameEditMode(visualizationMode)"
        />
      </a-tooltip>
    </div>

    <!-- <div v-if="isShowPreview" class="btn icon-text right" @click="onPreview">
      <a-icon-font class="icon" type="iconicon-chakan-copy" />
      {{ previewButton.name }}
    </div> -->

    <!-- <div
      v-if="isShowPublish"
      class="btn icon-text btn-with-text"
      @click="onPublish"
    >
      <a-icon-font class="icon" type="iconicon-fenxiang-copy" />
      发布
    </div> -->
    <template v-if="$route.name !== '可视化发布'">
      <info-header></info-header>
    </template>

    <a-modal v-model="publishModal" title="发布成功" :footer="null">
      <p>
        浏览器版本访问地址：<a :href="publishUrl" target="_blank">{{
          publishUrl
        }}</a>
      </p>
      <p>
        宽屏/VR版本访问地址：<a
          :href="`${publishUrl}?env=vr`"
          target="_blank"
          >{{ publishUrl + '?env=vr' }}</a
        >
      </p>
    </a-modal>
  </header>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import ProjectStore, { Project } from '@/store/modules/project'
import VisualizationStore from '@/store/modules/visualization'
import DataViewStore from '@/store/modules/dataview'
import UserStore from '@/store/modules/user'
import { publishDashboard } from '@/api/dashboard'
import {
  CHILD_ROUTE_METADATA,
  PREVIEW_PATH,
  //  VISUALIZATION_PATH
} from '@/router/studio'
import GraphBuild from '@/store/modules/graphbuild'
import InfoHeader from '@/components/home/InfoHeader.vue'

@Component({
  components: {
    InfoHeader,
  },
})
export default class StudioHeader extends Vue {
  public previewButton = {
    path: PREVIEW_PATH,
    name: '预览',
    icon: CHILD_ROUTE_METADATA[PREVIEW_PATH].icon,
  }

  public publishToken: string = ''
  public publishModal: boolean = false
  // 视图选择菜单折叠
  private collapsed: boolean = false
  // 面板收放按钮
  public isPanelCollapsed: boolean = true
  // 项目名称修改状态
  public projectNameEdit: boolean = false
  // 项目名称修改状态是否显示
  public projectNameEditShow: boolean = false

  mounted() {
    // 获取用户在项目下的角色
    if (this.projectId) {
      UserStore.getUserRole({
        projectId: this.projectId,
      })
    }
  }

  // 图构建页面， 项目名称后面跟节点名称
  public get graphBuildTaskName() {
    return this.$route.name === '图构建'
      ? `-${GraphBuild.graphBuildTaskName}`
      : ''
  }

  public get isPanelCollapsedVisualization() {
    return !VisualizationStore.isFullMode
  }

  public get projectId(): string {
    return (this.$route.params as any).id || localStorage.getItem('projectId')
  }

  public get isShowPreview(): boolean {
    if (
      this.$route.name === '系统构建' &&
      this.visualizationMode !== 'preview'
    ) {
      // 可视化视图才显示发布、预览按钮
      return true
    }
    return false
  }

  public get isShowPublish(): boolean {
    if (
      this.$route.name === '系统构建' &&
      this.visualizationMode !== 'preview' &&
      VisualizationStore.currentDashboard.id
    ) {
      return true
    }
    return false
  }

  public get isShowBackHome(): boolean {
    if (['preview', 'publish'].includes(this.visualizationMode)) {
      return false
    }
    return true
  }

  public get project(): Project | null {
    return ProjectStore.activeProject
  }

  public get visualizationMode(): string {
    return VisualizationStore.visualizationMode
  }

  public get publishUrl(): string {
    const { protocol, host } = window.location
    return `${protocol}//${host}/publish/${this.publishToken}`
  }

  public onPreview(): void {
    VisualizationStore.changeVisualizationMode('preview')
  }

  public onBackToEdit(): void {
    VisualizationStore.changeVisualizationMode('edit')
  }

  public onPublish(): void {
    const dashboardId = VisualizationStore.currentDashboard.id
    if (!dashboardId) {
      return
    }
    // 屏蔽没有组件的情况
    if (VisualizationStore.gridList.length === 0) {
      this.$message.error('面板不存在组件')
      return
    }
    // 先保存，在发布，排除发布后空白页的问题
    const VisualizationContent = VisualizationStore.VisualizationContent as any
    const me = this

    if (
      VisualizationContent &&
      typeof VisualizationContent.onSave === 'function'
    ) {
      const configurationWidget = VisualizationStore.gridList.filter(
        (gridItem) => gridItem.chartType === 'configuration'
      )
      const callback = () => {
        me.$confirm({
          title: '确定要发布吗？',
          content: '发布后可与他人分享可视化',
          okText: '确定',
          cancelText: '取消',
          onOk() {
            return new Promise((resolve, reject) => {
              publishDashboard({
                data: {
                  projectId: me.projectId,
                  id: dashboardId,
                  isComplex: configurationWidget.length > 0,
                  pipelineId: configurationWidget[0]
                    ? configurationWidget[0].chartOptions.pipelineId
                    : '',
                },
              })
                .then((response: any) => {
                  const publishToken = response.data.result
                  me.publishToken = publishToken
                  me.publishModal = true
                  // 这里最好需要将结果传递出来
                  resolve(response)
                })
                .catch(() => {
                  reject()
                })
            }).catch(() => console.log('publish errors!'))
          },
        })
      }
      VisualizationContent.onSave(true, callback)
    }
  }

  // 更新项目名称
  public async onUpdateProjectName() {
    const $input = document.querySelector(
      '#inputProjectName'
    ) as HTMLInputElement
    const newName = $input.value.trim()
    const originName = ProjectStore.activeProject?.name

    this.projectNameEdit = false
    if (!newName) {
      this.$message.warn('项目名称不能为空')
      return
    }

    if (originName === newName) {
      return
    }

    const projectId = ProjectStore.activeProject?.id
    const data = {
      id: projectId,
      name: newName,
    }

    const response = await ProjectStore.updateProjectInfoById(data)
    if (response.data.code === 100) {
      this.$message.info('修改成功')
    } else {
      this.$message.warning(response.data.message)
    }
    await ProjectStore.queryProjectById(`${projectId}`)
  }

  /**
   * 视图选择菜单折叠
   */

  public toggleCollapsed() {
    this.collapsed = !this.collapsed
    DataViewStore.setCollapsed(this.collapsed)
  }

  /**
   * 设置数据源算子面板的展开和收缩
   */
  public toggleSidePanelCollapsed() {
    this.isPanelCollapsed = !this.isPanelCollapsed
    DataViewStore.setSidePanel(this.isPanelCollapsed)
  }

  /**
   * 设置可视化视图组件面板的展开与收起
   */
  public toggleSidePanelCollapsedVisualization() {
    VisualizationStore.setIsFullMode(!VisualizationStore.isFullMode)
  }

  /**
   * 获取节点编辑面板1全屏状态
   */
  public get nodeEditPanelIsFullScreen() {
    return DataViewStore.nodeEditPanelIsFullScreen
  }

  /**
   * 处理项目名称修改回车事件
   */
  public inputEnter() {
    this.projectNameEdit = false
  }

  /**
   * 改变项目名称编辑状态
   */
  public changeProjectNameEditMode(mode: string) {
    if (mode === 'edit') {
      this.projectNameEdit = true
      this.$nextTick(() => {
        const inputProjectName: any = document.querySelector(
          '#inputProjectName'
        )
        inputProjectName.focus()
      })
    }
  }

  /**
   * 悬停显示项目名称编辑功能
   */
  public projectNameEditIsShow(mode: boolean) {
    this.projectNameEditShow = mode
  }

  // 返回
  public onHistoryBack() {
    this.$router.push('/management/projects')
  }
}
</script>

<style lang="less" scoped>
@import '@/constants';

header,
.header-style {
  align-items: center;
  background: @THEME_COLOR;
  color: #fff;
  display: flex;
  flex-direction: row;
  font-size: 1rem;
  height: @HEADER_HEIGHT;
  justify-content: space-between;
  padding-right: 10px;
  user-select: none;
}

.project-name {
  cursor: default;
  display: flex;
  flex: 1;
  font-size: 20px;
  font-weight: 700;
  justify-content: center;
  left: calc(50% - 310px);
  position: absolute;
  text-align: center;
  width: 620px;

  span {
    display: block;
    height: 32px;
    max-width: 600px;
    opacity: 0.9;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .project-name-icon {
    color: #fff;
    font-size: 14px;
    margin-left: 5px;
    margin-top: 7px;
    opacity: 0.8;

    &:hover {
      opacity: 1;
    }
  }
}

.btn-edit-project {
  cursor: pointer;
  font-size: 16px;
  margin-left: 10px;
}

.input-project-name {
  background-color: rgba(255, 255, 255, 0.2);
  color: rgba(255, 255, 255, 0.9);
  display: inline-block;
  font-size: 20px;
  font-weight: 700;
  max-width: 600px;
  text-align: center;
}

.btn {
  background-color: @THEME_COLOR;
  cursor: pointer;
  height: @HEADER_HEIGHT;
  line-height: @HEADER_HEIGHT;
  opacity: 0.8;
  text-align: center;
  transition: background-color 0.2s;

  &:hover {
    opacity: 1;
  }

  &.btn-back {
    margin-left: 10px;
  }
}

.btn.icon-only {
  font-size: 16px;

  .back-icon {
    font-size: 15px;
    transform: rotate(180deg);
  }
}

.btn.icon-text {
  padding: 0 15px;

  .icon {
    margin-right: 5px;
  }

  &.router-link-exact-active {
    background-color: @HIGHLIGHT_COLOR;
  }
}

.right {
  margin-left: auto;
}

.spliter {
  font-size: 16px;
  margin-left: 3px;
}

.back-area {
  display: inline-block;
  padding-right: 6px;
}

.collapsed-button {
  background-color: transparent;
  border-color: transparent;
  box-shadow: none;
  color: #fff;
  font-size: 16px;
  height: 28px;
  line-height: 28px;
  opacity: 0.8;
  padding: 0 5px;
  width: 28px;

  &:hover {
    opacity: 1;
  }
}
</style>
<style lang="less">
.project-name-tooltipbox {
  font-size: 14px;
  max-width: 400px;
  min-width: 20px;
  text-align: middle;
  width: auto;

  .ant-popover-inner-content {
    padding: 6px 8px;
  }
}
</style>
